package org.hwadee.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.hwadee.entity.Category;
import org.hwadee.entity.Post;
import org.hwadee.entity.User;
import org.hwadee.mapper.PostMapper;
import org.hwadee.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    PostMapper postMapper;

    public User login(User user) {
        return userMapper.selectUserByNameAndPass(user);
    }

    public int register(User user) {
        return userMapper.insertUser(user);
    }

    public User getUserByUsername(String username) {
        return userMapper.selectUserByUsername(username);
    }

    public User getUserById(Integer postUserId) {
        return userMapper.getUserById(postUserId);
    }

    public void updateUser(User user) {
        userMapper.updateUser(user);
    }

    public List<User> getAllUsers() {
        List<User> userList = userMapper.getAllUsers();
        for (int i = 0; i < userList.size(); i++) {
            Integer postCount = postMapper.countPostByUserId(userList.get(i).getUserId());
            userList.get(i).setPostCount(postCount);
        }
        return userList;
    }

    public void deleteUserById(Integer id) {
        userMapper.deleteUserById(id);
    }

    public void recoveryUserById(Integer id) {
        userMapper.recoveryUserById(id);
    }

    public List<User> getUsersByNickname(String search) {
        return userMapper.getUsersByNickname("%" + search + "%");
    }

    public PageInfo<User> pageUser(Integer pageIndex, Integer pageSize) {
        PageHelper.startPage(pageIndex, pageSize);
        List<User> userList = userMapper.getAllUsers();
        return new PageInfo<>(userList);
    }

    public String getNicknameById(Integer commentUserId) {
        return userMapper.getNicknameByUserId(commentUserId);
    }
}
